package yxy.game.pm2.module.niubee;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import yxy.apple.util.RandomUtility;
import yxy.apple.util.concurrent.ThreadPoolManager;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.weapongrade;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.Format;
import yxy.game.pm2.bean.Format.FormatType;
import yxy.game.pm2.bean.currency.CurrencyNotEnoughException;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.bean.pubsub.CurrencyPublisher;
import yxy.game.pm2.bean.task.Task;
import yxy.game.pm2.bean.task.TaskType;
import yxy.game.pm2.message.NiuBeeMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.battle.BattleHandle;
import yxy.game.pm2.module.hero.FormatHandle;
import yxy.game.pm2.module.playtype.PlayTypeHandle;
import yxy.game.pm2.module.playtype.PlayTypeModule;
import yxy.game.pm2.module.task.TaskHandle;
import yxy.game.pm2.module.tip.TipHandle;
import yxy.game.pm2.module.tip.TipType;

public class NiuBeeHandle {

    public void info(String playerCode, NiuBeeMessage.NiuBeeResponse.Builder response) {
        NiuBeeModule module = NiuBeeModule.get(playerCode);
        response.setAct(module.getProgress());
        response.setLevel(module.getLevel());
        response.setExp(module.getExp());
        response.setRefine(module.getRefineLevel());
        response.setSoul(module.getSoulLevel());
        response.setSkillLevel(module.getSkillLevel());

        for (Task task : module.task()) {
            if (task == null) {
                continue;
            }
            response.addTasks(TaskHandle.packTask(task));
        }
    }

    public Result reward(String playerCode, String taskCode, NiuBeeMessage.NiuBeeTaskBonusResponse.Builder response) {
        NiuBeeModule module = NiuBeeModule.get(playerCode);
        Task task = null;
        for (Task t : module.task()) {
            if (t.getCode().equals(taskCode)) {
                task = t;
                break;
            }
        }
        if (task == null || !task.isFinish() || task.isReward()) {
            return Result.TaskCantReward;
        }
        try {
            if (Task.lockTask(playerCode) && module.tryLock()) {
                {
                    Collection<Currency> rewards = new TaskHandle().rewardTask(playerCode, CCReason.神器, task);

                    response.setCode(taskCode);
                    response.addAllRewards(new CurrencyHandle().packItems(rewards));
                    // 激活
                    module.act();
                    response.setAct(module.getProgress());

                    Format format = new FormatHandle().get(playerCode, FormatType.普通);
                    if (format.getNb() == 0) {
                        format.setNb(module.getProgress());
                        Format.set(playerCode, FormatType.普通, format);
                    }
                }
                for (Task t : module.task()) {
                    if (t == null) {
                        continue;
                    }
                    response.addTasks(TaskHandle.packTask(t));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.DataError;
        } finally {
            Task.unlockTask(playerCode);
            module.unlock();
        }
        return Result.Success;
    }

    /**
     * 升级
     */
    public Result upgrade(String playerCode, NiuBeeMessage.NiuBeeUpgradeResponse.Builder response) {
        NiuBeeModule niuBeeModule = NiuBeeModule.get(playerCode);
        try {
            if (niuBeeModule.tryLock()) {
                if (niuBeeModule.getProgress() < 5) {
                    return Result.NiubeeNeedActiveAll;// 没有完全激活不能升级
                }
                weapongrade data = DataCenter.getData(niuBeeModule.getLevel() + 1, weapongrade.class);
                if (data == null) {
                    return Result.NiubeeLevelUpper;// 满级
                }
                data = DataCenter.getData(niuBeeModule.getLevel(), weapongrade.class);
                Collection<Currency> cost = Currency.create(data.getCosttype(), data.getCostid(), data.getCostnum());
                try {
                    new CurrencyHandle().cost(playerCode, CCReason.神器, cost);
                } catch (CurrencyNotEnoughException e) {
                    return new Result(Result.CostFail, e.getType().getNumber(), e.getDataId());// 消费不足
                }
                int expadd = RandomUtility.nextInt(data.getExpmin(), data.getExpmax() + 1);
                int exp = niuBeeModule.getExp() + expadd;
                niuBeeModule.setExp(exp);
                if (exp >= data.getExpuplv()) {
                    // 升级
                    niuBeeModule.setLevel(niuBeeModule.getLevel() + 1);
                    niuBeeModule.setExp(0);

                    PlayTypeHandle.saveWeapon(playerCode, PlayTypeModule.get(playerCode));
                    new BattleHandle().powerUpdate(playerCode);// 战力更新
                }

                niuBeeModule.set();

                response.setExp(niuBeeModule.getExp());
                response.setLevel(niuBeeModule.getLevel());

                Runnable runnable = () -> {
                    TaskHandle.handle(playerCode, TaskType.指标型_神器_等级_达到, niuBeeModule.getLevel());
                };
                ThreadPoolManager.getInstance().execute(runnable);

//				TaskHandle.handle(playerCode, TaskType.指标型_神器_等级_达到, niuBeeModule.getLevel());

                CurrencyPublisher.getInstance().publishMinus(playerCode, cost);
                if (DataCenter.getData(niuBeeModule.getLevel() + 1, weapongrade.class) == null) {
                    new TipHandle().updateTip(playerCode, TipType.神器_升级切页, false); // 满级
                }

                return Result.Success;

            }
        } catch (Exception e) {
        } finally {
            niuBeeModule.unlock();
        }
        return Result.DataError;
    }

    /**
     * 一键升级
     */
    public Result upgrade(String playerCode, NiuBeeMessage.NiuBeeUpgradeOneButtonResponse.Builder response) {
        NiuBeeModule niuBeeModule = NiuBeeModule.get(playerCode);
        try {
            if (niuBeeModule.tryLock()) {
                if (niuBeeModule.getProgress() < 5) {
                    return Result.NiubeeNeedActiveAll;// 没有完全激活不能升级
                }
                weapongrade data = DataCenter.getData(niuBeeModule.getLevel() + 1, weapongrade.class);
                if (data == null) {
                    return Result.NiubeeLevelUpper;// 满级
                }
                data = DataCenter.getData(niuBeeModule.getLevel(), weapongrade.class);

                //判断背包有没有消耗品  至少能消耗一次才进下一步
                if (Currency.number(playerCode, CurrencyType.CT_物品, 1026,false) < data.getCostnum()[0]) {
                    return Result.PackItemNumberLack;// 消费不足
                }

                //判断能否足够支持升级的消耗，能则直接升到下一级，不能则升到上限位置
                long num = 1;
                long expadd = RandomUtility.nextInt(data.getExpmin(), data.getExpmax() + 1);
                long exp = niuBeeModule.getExp() + expadd;
                while (exp <= data.getExpuplv()) {
                    expadd = RandomUtility.nextInt(data.getExpmin(), data.getExpmax() + 1);
                    exp = exp + expadd;
                    num++;
                }

                //数量不足，升到上限
                Currency cost = null;
                if (Currency.number(playerCode, CurrencyType.CT_物品, 1026,false) < data.getCostnum()[0] * num) {
                    long costNum = Currency.number(playerCode, CurrencyType.CT_物品, 1026,false) / data.getCostnum()[0];
                    cost = Currency.create(data.getCosttype()[0], data.getCostid()[0], data.getCostnum()[0] * costNum);
                    new CurrencyHandle().cost(playerCode, CCReason.神器, cost);
                    exp = niuBeeModule.getExp() + expadd * costNum;
                    niuBeeModule.setExp((int) exp);
                }

                //数量足够升级到下一级
                if (Currency.number(playerCode, CurrencyType.CT_物品, 1026,false) >= data.getCostnum()[0] * num) {
                    cost = Currency.create(data.getCosttype()[0], data.getCostid()[0], data.getCostnum()[0] * num);
                    new CurrencyHandle().cost(playerCode, CCReason.神器, cost);
                }

                if (exp >= data.getExpuplv()) {
                    // 升级
                    niuBeeModule.setLevel(niuBeeModule.getLevel() + 1);
                    niuBeeModule.setExp(0);
                }

                niuBeeModule.set();

                PlayTypeHandle.saveWeapon(playerCode, PlayTypeModule.get(playerCode));
                new BattleHandle().powerUpdate(playerCode);// 战力更新

                response.setExp(niuBeeModule.getExp());
                response.setLevel(niuBeeModule.getLevel());

                Runnable runnable = () -> {
                    TaskHandle.handle(playerCode, TaskType.指标型_神器_等级_达到, niuBeeModule.getLevel());
                };
                ThreadPoolManager.getInstance().execute(runnable);

                List<Currency> CurrencyList = new ArrayList<>();
                CurrencyList.add(cost);

                CurrencyPublisher.getInstance().publishMinus(playerCode, CurrencyList);
                if (DataCenter.getData(niuBeeModule.getLevel() + 1, weapongrade.class) == null) {
                    new TipHandle().updateTip(playerCode, TipType.神器_升级切页, false); // 满级
                }

                return Result.Success;

            }
        } catch (Exception e) {
        } finally {
            niuBeeModule.unlock();
        }
        return Result.DataError;
    }


}
